package com.zhuoyue.web.controller.system;

import com.zhuoyue.common.annotation.Log;
import com.zhuoyue.common.core.controller.BaseController;
import com.zhuoyue.common.core.domain.AjaxResult;
import com.zhuoyue.common.core.domain.entity.SysUser;
import com.zhuoyue.common.core.domain.entity.TblProductSeries;
import com.zhuoyue.common.core.page.TableDataInfo;
import com.zhuoyue.common.enums.BusinessType;
import com.zhuoyue.common.utils.DealLogUtils;
import com.zhuoyue.common.utils.SecurityUtils;
import com.zhuoyue.common.utils.ServletUtils;
import com.zhuoyue.common.utils.poi.ExcelUtil;
import com.zhuoyue.system.domain.TblProductInfo;
import com.zhuoyue.system.mapper.ProductInfoMapper;
import com.zhuoyue.system.service.*;
import com.zhuoyue.web.utils.OrgCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * oss图片展示以及新增
 *
 * @author hewenze
 * @date 2020-08-21
 */
@RestController
@RequestMapping("/system/productInfo")
public class ProductInfoController extends BaseController {
    @Autowired
    private IProductInfoService productInfoService;

    @Autowired
    private ISysImageCategoryService categoryService;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private ISysProductManageService productManageService;

    @Autowired
    private ISysReleaseLogService releaseLogService;

    @Autowired
    private OrgCodeUtils orgCodeUtils;

    @Autowired
    private DealLogUtils dealLogUtils;

    /**
     * 查询产品信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TblProductInfo sysImage) {
        // 若按分类查询, 则先根据分类查询其下的系列, 在合并系列ID
        if (sysImage.getSelectClassifyId() != null) {
            List<TblProductSeries> seriesList = productManageService.selectSeriesByClassifyId(sysImage.getSelectClassifyId());
            List<Long> seriesIdList = seriesList.stream().map(TblProductSeries::getId).collect(Collectors.toList());
            String selectSeriesIdList = org.apache.commons.lang3.StringUtils.join(seriesIdList, ',');
            sysImage.setSelectSeriesIdList(selectSeriesIdList);
        }
        // 若按系列查询
        if (sysImage.getSelectSeriesId() != null) {
            sysImage.setSelectSeriesIdList(sysImage.getSelectSeriesId().toString());
        }
        startPage();
        List<TblProductInfo> list = productInfoService.selectProductInfoList(sysImage);
        return getDataTable(list);
    }

    /**
     * 查询产品信息列表
     */
    @GetMapping("/export")
    public AjaxResult export(TblProductInfo sysImage) {
        // 若按分类查询, 则先根据分类查询其下的系列, 在合并系列ID
        if (sysImage.getSelectClassifyId() != null) {
            List<TblProductSeries> seriesList = productManageService.selectSeriesByClassifyId(sysImage.getSelectClassifyId());
            List<Long> seriesIdList = seriesList.stream().map(TblProductSeries::getId).collect(Collectors.toList());
            String selectSeriesIdList = org.apache.commons.lang3.StringUtils.join(seriesIdList, ',');
            sysImage.setSelectSeriesIdList(selectSeriesIdList);
        }
        // 若按系列查询
        if (sysImage.getSelectSeriesId() != null) {
            sysImage.setSelectSeriesIdList(sysImage.getSelectSeriesId().toString());
        }
        List<TblProductInfo> list = productInfoService.selectProductInfoList(sysImage);
        ExcelUtil<TblProductInfo> util = new ExcelUtil<>(TblProductInfo.class);
        return util.exportExcel(list, "产品信息");
    }


    /**
     * APP查询产品信息列表
     */
    @GetMapping("/listForApp")
    public TableDataInfo listForApp(TblProductInfo sysImage) {
        List<TblProductInfo> list = productInfoService.selectProductInfoListForApp(sysImage);
        return getDataTable(list);
    }

    /**
     * APP查询产品信息列表
     */
    @GetMapping("/getLatestUpdateTime")
    public AjaxResult getLatestUpdateTime() {
        LocalDateTime latestUpdateTimeOfApp = releaseLogService.getLatestCreateTime();
        return AjaxResult.success(latestUpdateTimeOfApp);
    }


    /**
     * 修改产品信息(不删除原本的图片)
     */
    @Log(title = "产品信息修改", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('product:info:edit')")
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody TblProductInfo productInfo) {
        // 修改前的数据
        TblProductInfo sourceData = productInfoService.selectProductInfoById(productInfo.getId());
        String classAndMethodName = this.getClass().getName() + "." + "edit()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();

        // 若自动入网为'Y', 则将同类型下其他所有产品的自动入网设置为'N'
        if ("Y".equals(productInfo.getZdrw())) {
            productInfoService.setZdrwDisableOfCategory(productInfo.getCategoryId());
        }

        productInfo.setUpdateBy(SecurityUtils.getUsername());
        productInfoService.updateProductInfo(productInfo);

        // 修改后的数据
        TblProductInfo targetData = productInfoService.selectProductInfoById(productInfo.getId());
        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, sourceData, targetData);
        return AjaxResult.success();
    }

    /**
     * 添加产品信息
     *
     * @param productInfo
     * @return
     * @throws IOException
     */
    @Log(title = "产品信息添加", businessType = BusinessType.INSERT)
    @PostMapping("/addProductInfo")
    public AjaxResult addProductInfo(@RequestBody TblProductInfo productInfo) {
        String classAndMethodName = this.getClass().getName() + "." + "addProductInfo()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();

        // 若自动入网为'Y', 则将同类型下其他所有产品的自动入网设置为'N'
        if ("Y".equals(productInfo.getZdrw())) {
            productInfoService.setZdrwDisableOfCategory(productInfo.getCategoryId());
        }
        productInfo.setCreateBy(SecurityUtils.getUsername());
        this.productInfoService.insertSysImage(productInfo);

        // 添加后的数据
        TblProductInfo targetData = productInfoService.selectProductInfoById(productInfo.getId());
        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, null, targetData);
        return AjaxResult.success();
    }

    /**
     * 删除产品信息(不删除图片)
     */
    @Log(title = "产品信息删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{productInfoId}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable String productInfoId) {
        TblProductInfo productInfo = productInfoService.selectProductInfoById(productInfoId);

        String classAndMethodName = this.getClass().getName() + "." + "remove()";
        SysUser user = orgCodeUtils.getLoginUser(ServletUtils.getRequest()).getUser();

//        this.fileUploadService.delete(productInfo.getPZImageUID());
//        // 若展示图与入网图不一致, 则继续删除入网图
//        if (!productInfo.getPZImageUID().equals(productInfo.getPRImageUID())) {
//            this.fileUploadService.delete(productInfo.getPRImageUID());
//        }

        productInfoService.deleteSysImageByIds(productInfoId);

        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, productInfo, null);
        return AjaxResult.success();
    }

    /**
     * @return
     * @author lastwhisper
     * @desc 根据文件名下载oss上的文件
     * @Param objectName
     */
    @RequestMapping("file/download")
    @ResponseBody
    public void download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {


        //通知浏览器以附件形式下载

        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "ISO-8859-1"));
        //response.setHeader("Content-Disposition","attachement");

        this.fileUploadService.exportOssFile(response.getOutputStream(), objectName);
    }


    @Autowired
    private ProductInfoMapper productInfoMapper;

    /**
     * 步骤一:修改ID
     *
     * @return
     */
    @Deprecated
//    @GetMapping("/modifyId")
    private AjaxResult modifyId() {
        List<TblProductInfo> productInfoList = productInfoService.selectProductInfoList(new TblProductInfo());
        List<TblProductInfo> modifyIdList = new ArrayList<>();

        for (TblProductInfo tblProductInfo : productInfoList) {
            String pzImageUID = tblProductInfo.getPZImageUID();
            String zUID = pzImageUID.substring(pzImageUID.lastIndexOf('/') + 1, pzImageUID.lastIndexOf('.'));
            if (!zUID.equals(tblProductInfo.getId())) {
                TblProductInfo info = new TblProductInfo();
                info.setId(zUID);
                info.setPZImageUID(tblProductInfo.getPZImageUID());
                modifyIdList.add(info);
            }
        }

        for (TblProductInfo id : modifyIdList) {
            productInfoMapper.updateIdByZImageUid(id);
            productInfoMapper.updateIdByZImageUidAPP(id);
        }

        return AjaxResult.success(modifyIdList);
    }


    /**
     * 展示图与入网图一致
     * 步骤二:复制一份展示图作为入网图, 加"_1"后缀
     *
     * @return
     */
    @Deprecated
//    @GetMapping("/modifyWhenSame")
    private AjaxResult modifyWhenSame() {
        List<TblProductInfo> productInfoList = productInfoService.selectProductInfoList(new TblProductInfo());
        List<String> idList = new ArrayList<>();
        List<TblProductInfo> modifyProductInfoList = new ArrayList<>();

        for (TblProductInfo tblProductInfo : productInfoList) {
            if (isImageUidEqual(tblProductInfo.getPZImageUID(), tblProductInfo.getPRImageUID())) {
                TblProductInfo info = new TblProductInfo();
                String id = tblProductInfo.getId();
                info.setId(id);
                info.setPZImageUID(tblProductInfo.getPZImageUID());
                info.setPRImageUID(insertSubstrInLastTargetStr(tblProductInfo.getPRImageUID(), ".", "_1"));
                info.setPRUrl(insertSubstrInLastTargetStr(tblProductInfo.getPRUrl(), ".", "_1"));
                info.setPROssUrl(insertSubstrInLastTargetStr(tblProductInfo.getPROssUrl(), ".", "_1"));
                modifyProductInfoList.add(info);
            }
        }

        for (TblProductInfo productInfo : modifyProductInfoList) {
//            fileUploadService.copyFile(productInfo.getPZImageUID(), productInfo.getPRImageUID());
            productInfoMapper.updateRImageByid(productInfo);
            productInfoMapper.updateRImageByidAPP(productInfo);
        }


        return AjaxResult.success(idList);
    }

    private String insertSubstrInLastTargetStr(String sourceStr, String targetStr, String subStr) {
        StringBuilder stringBuilder = new StringBuilder(sourceStr);
        stringBuilder.insert(stringBuilder.lastIndexOf(targetStr), subStr);
        return stringBuilder.toString();
    }

    /**
     * 展示图与入网图不一致
     * 步骤三:复制入网图并修改名称, 名称为主键ID+"_1"
     *
     * @return
     */
    @Deprecated
//    @GetMapping("/modifyWhenDiff")
    private AjaxResult modifyWhenDiff() {
        List<TblProductInfo> productInfoList = productInfoService.selectProductInfoList(new TblProductInfo());
        List<String> idList = new ArrayList<>();
        List<TblProductInfo> modifyProductInfoList = new ArrayList<>();

        for (TblProductInfo tblProductInfo : productInfoList) {
            if (!isImageUidEqual(tblProductInfo.getPZImageUID(), tblProductInfo.getPRImageUID())) {
//                fileUploadService.copyFile(tblProductInfo.getPRImageUID(), insertSubstrInLastTargetStr(tblProductInfo.getPZImageUID(), ".", "_1"));

                TblProductInfo info = new TblProductInfo();
                String id = tblProductInfo.getId();
                info.setId(id);
                info.setPRImageUID(insertSubstrInLastTargetStr(tblProductInfo.getPZImageUID(), ".", "_1"));
                info.setPRUrl(insertSubstrInLastTargetStr(tblProductInfo.getPZUrl(), ".", "_1"));
                info.setPROssUrl(insertSubstrInLastTargetStr(tblProductInfo.getPZOssUrl(), ".", "_1"));
                modifyProductInfoList.add(info);
                idList.add(id);
            }
        }

        for (TblProductInfo productInfo : modifyProductInfoList) {
            productInfoMapper.updateRImageByid(productInfo);
            productInfoMapper.updateRImageByidAPP(productInfo);
        }


        return AjaxResult.success(idList);
    }

    private boolean isImageUidEqual(String pZUid, String pRUid) {
        if (pRUid.indexOf('_') < 0) {
            return pZUid.equals(pRUid);
        }

        StringBuilder stringBuilder = new StringBuilder(pRUid);
        int index = stringBuilder.lastIndexOf("_");
        String substring = stringBuilder.substring(0, index) + stringBuilder.substring(index + 2);
        return pZUid.equals(substring);
    }
}